package com.joysuch.wwyt.config;

import cn.hutool.json.JSONUtil;
import com.joysuch.wwyt.edu.bean.EduDoExamResultBean;
import com.joysuch.wwyt.edu.service.EduExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import org.springframework.data.redis.connection.Message;

/**
 * @author : zhangzhe
 * @date : 2023/7/27
 */
@Component
@PropertySource(value = "classpath:redis.properties", encoding = "UTF-8")
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private RedisClient redisClient;
    @Autowired
    private EduExamService eduExamService;
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 重写omMessage方法，当Redis中的Key过期时会执行该方法
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 过期的key
        String expireKey = message.toString();
        cacheAnswers(expireKey);
    }

    private void cacheAnswers(String expireKey) {
        if (expireKey.startsWith("CACHETES")) {
            String[] split = expireKey.split(":");
            expireKey = "CACHE_ANSWERS:" + split[1]+":" +split[2];
            String result = redisClient.get(expireKey);
            EduDoExamResultBean eduDoExamResultBean = JSONUtil.toBean(result, EduDoExamResultBean.class);
            if (eduDoExamResultBean != null){
            eduDoExamResultBean.setIsSubmit(1);
            eduExamService.submit(eduDoExamResultBean,eduDoExamResultBean.getResultByUserId(),eduDoExamResultBean.getIsSubmit());
            eduExamService.cacheAnswers(eduDoExamResultBean,eduDoExamResultBean.getResultByUserId(),2);
            }
        }
    }

}
